package co.edu.unal.franquicias.mastercard.auth;

import com.sun.jersey.api.view.Viewable;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;

/**
 * Status resource.
 * Sub-resource available at the following path:
 * <pre>/{user}/statuses/{statusId}</pre>
 */
public class StatusResource extends ResourceBase {
    private final int statusId;

    StatusResource(int statusId, StatusesResource parent) {
        super(parent);
        this.statusId = statusId;
    }

    /**
     * Gets an HTML representation of a status (by ID).
     *
     * @return HTML representation of the status
     */
    @GET
    @Produces(MediaType.TEXT_HTML)
    public Viewable getHtml() {
        checkUser();
        Status status = DataProvider.getStatus(user, statusId);
        return new Viewable("/status", status);
    }

    /**
     * Updates the note and redirects to the list of all statuses.
     *
     * @param text status message
     * @return redirect to list of statuses
     */
    @POST
    public Response post(@FormParam("text") String text) {
        checkUser();
        checkWrite();
        DataProvider.updateStatus(user, statusId, text);
        return Response.seeOther(UriBuilder.fromPath(uriInfo.getMatchedURIs().get(1)).build()).build();
    }

    /**
     * Deletes the note and redirects back to the list of all notes.
     */
    @DELETE
    public void delete() {
        checkUser();
        checkWrite();
        DataProvider.deleteStatus(user, statusId);
    }
}
